﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Oracle.DataAccess.Client;
using System.Data;
using System.Windows.Forms;
using System.Configuration;

namespace Audit_Configuration_Oracle.Model
{
    public class DBConnection
    {
        public OracleConnection conn { get; set; }
        public ConnectionString cnx { get; set; }
        //private string msgError { get; set; }

        public DBConnection()
        {
            conn = null;
            cnx = null;
        }

        public void openConnection()
        {
            this.openConnection(cnx.username, cnx.password, cnx.database);
        }

        public bool openConnection(string username, string password, string schema)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            connectionString = string.Format(connectionString, cnx.database, cnx.username, cnx.password);

            bool connected = false;
            try
            {
                conn = new OracleConnection(connectionString);

                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
             
                if (cmd.Connection.State == ConnectionState.Closed)
                {
                    conn.Open();
                    connected = true;
                }
            }
            catch (OracleException e) 
            {
                MessageBox.Show(e.Message, "Connection Error", MessageBoxButtons.OK);
            }

            return connected;
        }

        public void closeConnection()
        {
            try
            {
                OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                if (cmd.Connection.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
                conn = null;
            }
        }
    }
}
